package A10_读写锁_ReentrantReadWriteLock;


import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 写写、写读互斥
 * 读读 不互斥
 * @Author: KingWang
 * @Date: 2021/5/23
 * @Desc:
 **/
public class ReadWriteLockDemo {

    public static void main(String[] args) throws InterruptedException {


        MyCache cache = new MyCache();
        for (int i = 0; i < 5; i++) {
            final int  tempInt = i;
            new Thread(() -> {
                cache.put(String.valueOf(tempInt), UUID.randomUUID().toString().substring(0,8));
            },String.valueOf(i)).start();
        }

        TimeUnit.SECONDS.sleep(1);

        for (int i = 0; i <5 ; i++) {
            final int tempInt = i;
            new Thread(() -> {
                cache.get(String.valueOf(tempInt));
            },String.valueOf(i)).start();
        }

    }
}

class MyCache{

    private volatile Map<String, String> cache = new HashMap<>();
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void put(String key,String value){
        lock.writeLock().lock();
        try{
            System.out.println(Thread.currentThread().getName() +" \t 开始写入");
            TimeUnit.SECONDS.sleep(1);
            cache.put(key,value);
            System.out.println(Thread.currentThread().getName() + "\t 写入成功");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }

    }

    public void get(String key){
        lock.readLock().lock();
        String result = null;
        try{
            System.out.println(Thread.currentThread().getName() + "\t 开始读取");
            TimeUnit.SECONDS.sleep(1);
            result =  cache.get(key);
            System.out.println(Thread.currentThread().getName() + "\t 读取到值：" + result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

}
